/*
 * Copyright (C) 2020 The YouTike.com Authors.
 * https://www.youtike.com
 */

package com.qdxwx.manage.interceptor;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.manager.Manager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author ZhiYong
 * @createTime 2020/7/24 14:21
 * @description
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        Manager manager = SessionUtils.getManager(request);
        if (manager == null || manager.getManagerId() == 0) {
            response.sendRedirect("/auth/login.html");
            return false;
        }
        //ManagerUtils.isAdmin = ManagerUtils.isAdmin(request);
        //Editor manager = editorService.findByUserId(passport.getId());
        //if (manager != null) {
        //    ManagerUtils.bankId = manager.getBankId();
        //}
        //Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        //Cookie[] cookies = request.getCookies();
        //if (null != cookies) {
        //    for (Cookie cookie : cookies) {
        //        cookieMap.put(cookie.getName(), cookie);
        //    }
        //}
        //System.out.println("cookieSize:" + cookieMap.size());
        //for (String name : cookieMap.keySet()) {
        //    System.out.println("Cache(" + name + "):" + cookieMap.get(name).getValue());
        //}
        // 最后的情况就是进入登录页面
        return true;
        //return false;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception {
        //System.out.println("拦截postHandle...");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception {
        //System.out.println("拦截afterCompletion...");
    }
}
